<template>
  <div class="clearfix">
    <a-upload
      action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
      listType="picture-card"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length<=num">
        <a-icon type="plus" />
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
export default {
  name: 'upload',
  props: {
    num: {
      type: Number,
      require: false,
      default: 0
    }
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  methods: {
    beforeUpload(file) {
      console.log(file)
      let size = file.size / 1024 / 1024
      console.log(size)
    },
    handleCancel() {
      this.previewVisible = false
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
      let flag = true
      if (fileList.length >= this.num) {
        fileList.map(item => {
          if (!item.response) {
            flag = false
          }
        })
        if (flag) {
          let imgArr = fileList.map(
            item => item.response.thumbUrl || item.response.url
          )
          this.$emit('uploadSuccess', {
            imgArr
          })
        }
      }
    }
  }
}
</script>
<style>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
